package com.quanxiaoha.xiaohashu.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.quanxiaoha.xiaohashu.gateway.constant.RedisKeyConstants;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 自定义权限验证接口拓展
 */
@Component
@Slf4j
public class StpInterfaceImpl implements StpInterface {

    @Resource
    RedisTemplate<String, String> redisTemplate;
    @Qualifier("objectMapper")
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    @SneakyThrows
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的权限列表
        log.info("## 获取用户权限列表, loginId: {}", loginId);
        //构建用户-角色的Redis key
        String userRolesKey = RedisKeyConstants.buildUserRoleKey(Long.valueOf(loginId.toString()));
        //获取该用户的角色集合
        String userRolesValue = redisTemplate.opsForValue().get(userRolesKey);

        if (StringUtils.isBlank(userRolesValue)) {
            return null;
        }
        //把该用户所有的角色对象转换为角色集合
        List<String> userRoleKeys =objectMapper.readValue(userRolesValue, new TypeReference<>() {});

        if(CollUtil.isNotEmpty(userRoleKeys)){
            List<String> rolePermissionsKeys = userRoleKeys.stream().map(RedisKeyConstants::buildRolePermissionsKey).toList();
            List<String> rolePermissionsValues = redisTemplate.opsForValue().multiGet(rolePermissionsKeys);
            if(CollUtil.isNotEmpty(rolePermissionsValues)){
                List<String> permissions = new ArrayList<>();
                rolePermissionsValues.forEach(jsonValue -> {
                    try {
                        // 将 JSON 字符串转换为 List<String> 权限集合
                        List<String> rolePermissions = objectMapper.readValue(jsonValue, new TypeReference<>() {});//重复上面的那一步，json转化为string
                        permissions.addAll(rolePermissions);//// TypeReference 通过匿名内部类的方式保留泛型信息
                    } catch (JsonProcessingException e) {
                        log.error("==> JSON 解析错误: ", e);
                    }
                });
                return permissions;
            }
        }


        //todo 从redis中获取
        return Collections.emptyList();
    }

    @Override
    @SneakyThrows
    public List<String> getRoleList(Object loginId, String loginType) {
        //返回此loginId拥有的角色列表
        log.info("## 获取用户角色列表, loginId: {}", loginId);
        //获取用户-角色的Redis key
        String userRolesKey = RedisKeyConstants.buildUserRoleKey(Long.valueOf(loginId.toString()));

        //获取该用户的角色集合
        String userRolesValue = redisTemplate.opsForValue().get(userRolesKey);
        if(StringUtils.isBlank(userRolesValue)){
            return null;
        }

        //todo 从redis中获取
        return objectMapper.readValue(userRolesValue, new TypeReference<>() {
        });
    }
}
